package flc.ast.fragment;

import android.app.Dialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.LocalVideoActivity;
import flc.ast.activity.VideoActivity;
import flc.ast.adapter.VideoCategoryAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.databinding.FragmentVideoBinding;
import flc.ast.dialog.InputPasswordDialog;
import flc.ast.dialog.SetAnswerDialog;
import flc.ast.dialog.SetPasswordDialog;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ViideoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class VideoFragment extends BaseNoModelFragment<FragmentVideoBinding> {

    private List<MyAlbumBean> listShow = new ArrayList<>();
    private VideoCategoryAdapter categoryAdapter;
    private Dialog myAddCategoryDialog;
    private EditText dialogAdd;
    private String pwd;

    @Override
    protected int onCreate() {
        return R.layout.fragment_video;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.ivAdd.setOnClickListener(this);
        mDataBinding.flLocalVideo.setOnClickListener(this);
        mDataBinding.flPrivacyFile.setOnClickListener(this);

        mDataBinding.rvVideoCategoryList.setLayoutManager(new GridLayoutManager(mContext, 2));
        categoryAdapter = new VideoCategoryAdapter();
        mDataBinding.rvVideoCategoryList.setAdapter(categoryAdapter);
        categoryAdapter.setOnItemClickListener(this);

    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAdd:
                //新建视频分类弹框
                addCategoryDialog();
                myAddCategoryDialog.show();
                break;
            case R.id.flLocalVideo://本地视频
                getPermission();
                break;
            case R.id.flPrivacyFile://隐私文件
                //是否完成设置密码
                boolean isSetPassword = SPUtil.getBoolean(getContext(), Content.isHavePassword, false);
                if (isSetPassword) {
                    inputPasswordDialog();
                } else {
                    setPasswordDialog();
                }
                break;
            //新建相册弹框
            case R.id.tvDialogAddCategoryConfirm://确定
                addCategory();
                break;
            case R.id.tvDialogAddCategoryCancel://取消
                myAddCategoryDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        VideoActivity.categoryName = listShow.get(position).getName();
        startActivity(VideoActivity.class);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
        setData();
    }

    private void getPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_manage_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                startActivity(LocalVideoActivity.class);
            }
        }).request();
    }

    //获取视频和图片数据
    private void setData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    long size = 0;
                    for (SelectMediaEntity selectMediaEntity : selectMediaEntities) {
                        size += selectMediaEntity.getSize();
                    }
                    mDataBinding.tvLocalVideoNum.setText(getString(R.string.video_num, selectMediaEntities.size(), ConvertUtils.byte2FitMemorySize(size, 1)));
                } else {
                    mDataBinding.tvLocalVideoNum.setText(getString(R.string.video_num, 0, "0.0B"));
                }
            }
        });
    }

    private void getData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                List<File> data = FileUtils.listFilesInDir(path + "/" + file.getName());
                List<String> list = new ArrayList<>();
                for (File datum : data) {
                    list.add(datum.getPath());
                }
                listShow.add(new MyAlbumBean(file.getName(), list));
            }
        }
        if (listShow.size() > 0) {
            categoryAdapter.setList(listShow);
            mDataBinding.rvVideoCategoryList.setVisibility(View.VISIBLE);
            mDataBinding.tvVideoCategoryNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvVideoCategoryList.setVisibility(View.GONE);
            mDataBinding.tvVideoCategoryNoData.setVisibility(View.VISIBLE);
        }
    }

    private void addCategory() {
        String categoryName = dialogAdd.getText().toString();
        if (TextUtils.isEmpty(categoryName)) {
            ToastUtils.showShort(R.string.please_input_category_name);
            return;
        }
        myAddCategoryDialog.dismiss();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo + "/" + categoryName;
        if (FileUtils.isFileExists(path)) {
            ToastUtils.showShort(getString(R.string.category_is_exist));
        } else {
            FileUtils.createOrExistsDir(path);
            ToastUtils.showShort(getString(R.string.add_category_suc));
        }
        getData();
    }

    //新建视频分类弹框
    private void addCategoryDialog() {
        myAddCategoryDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_category, null);
        myAddCategoryDialog.setContentView(inflate);
        myAddCategoryDialog.setCancelable(true);
        Window dialogWindow = myAddCategoryDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogAddCategoryConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogAddCategoryCancel);
        dialogAdd = inflate.findViewById(R.id.etDialogAddCategoryText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    private void setPasswordDialog() {
        SetPasswordDialog setPasswordDialog = new SetPasswordDialog(mContext);
        setPasswordDialog.setListener(new SetPasswordDialog.Ilistener() {
            @Override
            public void click(String password) {
                pwd = password;
                setAnswerDialog();
            }
        });
        setPasswordDialog.show();
    }

    private void setAnswerDialog() {
        SetAnswerDialog setAnswerDialog = new SetAnswerDialog(mContext);
        setAnswerDialog.setListener(new SetAnswerDialog.Listener() {
            @Override
            public void setPassword(String question, String answer) {
                //记录密码
                SPUtil.putBoolean(getContext(), Content.isHavePassword, true);
                SPUtil.putString(getContext(), Content.myPassword, pwd);
                SPUtil.putString(getContext(), Content.myProblem, question);
                SPUtil.putString(getContext(), Content.myAnswer, answer);
            }
        });
        setAnswerDialog.show();
    }

    private void inputPasswordDialog() {
        InputPasswordDialog inputPasswordDialog = new InputPasswordDialog(mContext);
        inputPasswordDialog.setListener(new InputPasswordDialog.Ilistener() {
            @Override
            public void click() {
                forgetPasswordDialog();
            }
        });
        inputPasswordDialog.show();
    }

    private void forgetPasswordDialog() {
        SetAnswerDialog setAnswerDialog = new SetAnswerDialog(mContext);
        setAnswerDialog.isForget = true;
        setAnswerDialog.setListener(new SetAnswerDialog.Listener() {
            @Override
            public void setPassword(String question, String answer) {
                changePasswordDialog();
            }
        });
        setAnswerDialog.show();
    }

    private void changePasswordDialog() {
        SetPasswordDialog setPasswordDialog = new SetPasswordDialog(mContext);
        setPasswordDialog.setListener(new SetPasswordDialog.Ilistener() {
            @Override
            public void click(String password) {
                SPUtil.putString(getContext(), Content.myPassword, password);
            }
        });
        setPasswordDialog.show();
    }

}